package com.agile.leetcode.redis.bloomfilter;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;

import java.nio.charset.Charset;

/**
 * 谷歌的guavva关于布隆过滤器的实现
 *
 * @Author:ChenZhangKun
 * @Date: 2021/9/23 16:20
 */
public class BloomFilterUtil {
    private static BloomFilterUtil instance;

    /**
     * 私有构造
     */
    private BloomFilterUtil() {
    }

    /**
     * 静态内部类的方式
     */
    private static class BloomFilterUtilInstance {
        private static final BloomFilterUtil INSTANCE = new BloomFilterUtil();
    }

    public static BloomFilterUtil getInstance() {
        return BloomFilterUtilInstance.INSTANCE;
    }

    /**
     * 预估量
     */
    private static final int INSERTIONS = 10_0000;
    /**
     * 错误率
     */
    private static final double FPP = 0.0001;
    /**
     * 布隆过滤器
     */
    private BloomFilter<String> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), INSERTIONS, FPP);

    /**
     * 添加元素
     *
     * @param element
     */
    public void addElement(String element) {
        bloomFilter.put(element);
    }

    /**
     * 是否包含
     *
     * @param element
     * @return
     */
    public boolean mightContainer(String element) {
        return bloomFilter.mightContain(element);
    }
}
